﻿using System.IO;
using MySql.Data.MySqlClient;
using Ymatou.Evaluate.Common;
using Ymatou.Evaluate.Entity;
using Dapper;
using System;
using System.Collections.Generic;
using Ymatou.CommonService;
using System.Linq;

namespace Ymatou.Evaluate.Data.Operator
{
    public class EvaluateOperatorData
    {
        #region 洗数据用

        /// <summary>
        /// 读取需要洗的数据
        /// </summary>
        /// <returns></returns>
        [Obsolete("洗数据用")]
        public static List<BaseEvaluate> GetBaseEvaluateList(List<int> orderIds)
        {
            string whereSQL = "";
            if (orderIds != null && orderIds.Count > 0)
            {
                whereSQL = " AND OrderId IN(" + string.Join(",", orderIds) + ")";
            }
            var sql = string.Format(@"SELECT a.OrderId,a.BuyerId,a.SellerId,a.confirmedTime AS AddTime FROM order_tmp0406 a WHERE a.isync=0 AND NOT EXISTS(SELECT * FROM evaluateorderstatus b WHERE a.orderid=b.OrderId) {0};", whereSQL);
            using (var conn = new MySqlConnection(ConnectionStringHelper.EvaluateDBReadConnectionString))
            {
                try
                {
                    var list = conn.Query<BaseEvaluate>(sql).ToList();
                    return list;
                }
                catch (Exception ex)
                {
                    ApplicationLog.Error(string.Format("GetBaseEvaluateList发生SQL异常：{0}", ex.Message), ex);
                }
            }
            return null;
        }

        /// <summary>
        /// 更新洗数据结果
        /// </summary>
        /// <param name="buyerId"></param>
        /// <param name="orderId"></param>
        /// <param name="sellerId"></param>
        /// <returns></returns>
        [Obsolete("洗数据用")]
        public static bool UpdateBaseEvaluate(int orderId, int buyerId, int sellerId, DateTime addTime)
        {
            using (MySqlConnection conn = new MySqlConnection(ConnectionStringHelper.EvaluateDBWriteConnectionString))
            {
                var data = false;
                string osql = @"UPDATE order_tmp0406
                               SET isync=1
                               WHERE BuyerId=@BuyerId AND SellerId=@SellerId AND OrderId=@OrderId;";

                //更新订单评价时间
                string orderStatusSql = @"UPDATE evaluateorderstatus SET AddTime=@AddTime WHERE OrderId=@OrderId AND SellerId=@SellerId AND BuyerId=@BuyerId;
                                          UPDATE evaluateprodstatus SET AddTime=@AddTime WHERE OrderId=@OrderId AND SellerId=@SellerId AND BuyerId=@BuyerId;";
                conn.Open();
                var tran = conn.BeginTransaction();
                try
                {
                    var count = conn.Execute(osql, new { BuyerId = buyerId, SellerId = sellerId, OrderId = orderId }, tran);
                    if (count > 0)
                    {
                        count = conn.Execute(orderStatusSql, new { BuyerId = buyerId, SellerId = sellerId, OrderId = orderId, AddTime = addTime }, tran);
                        if (count > 0)
                        {
                            tran.Commit();
                            data = true;
                        }
                        else
                        {
                            tran.Rollback();
                        }
                    }
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    ApplicationLog.Error(string.Format("UpdateBaseEvaluate发生SQL异常SQL:【{0}】", osql), ex);
                }
                conn.Close();
                return data;
            }
        }

        /// <summary>
        /// 读取需要洗的数据
        /// </summary>
        /// <returns></returns>
        [Obsolete("洗数据用")]
        public static List<EvaluateProduct> GetSocialComposite(List<int> orderIds, out List<EvaluateImgs> imgs)
        {
            imgs = new List<EvaluateImgs>();
            string whereSQL1 = "";
            string whereSQL2 = "";
            if (orderIds != null && orderIds.Count > 0)
            {
                whereSQL1 = " AND OrderId IN(" + string.Join(",", orderIds) + ")";
                whereSQL2 = string.Format(" WHERE NoteId IN(SELECT NoteId FROM ymtsocialcomposite WHERE IsSync='0' {0})", whereSQL1);
            }
            var sql = string.Format(@"SELECT NoteId AS ProdEvalId,OrderId,SellerId,BuyerId,ProductId,Comments,EvalTime AS ProdEvalTime FROM ymtsocialcomposite where IsSync='0' {0};", whereSQL1);
            var imgsql = string.Format(@"SELECT NoteId AS ProdEvalId,Imgs AS ImgUrl FROM ymtsocialpic {0};", whereSQL2);

            using (var conn = new MySqlConnection(ConnectionStringHelper.EvaluateDBReadConnectionString))
            {
                try
                {
                    var list = conn.Query<EvaluateProduct>(sql).ToList();
                    imgs = conn.Query<EvaluateImgs>(imgsql).ToList();
                    return list;
                }
                catch (Exception ex)
                {
                    ApplicationLog.Error(string.Format("GetEvaluateProductImg发生SQL异常：{0}", ex.Message), ex);
                }
            }
            return null;
        }

        /// <summary>
        /// 更新洗数据结果
        /// </summary>
        /// <param name="buyerId"></param>
        /// <param name="orderId"></param>
        /// <param name="sellerId"></param>
        /// <returns></returns>
        [Obsolete("洗数据用")]
        public static bool UpdateSocialComposite(int orderId, int buyerId, int sellerId)
        {
            using (MySqlConnection conn = new MySqlConnection(ConnectionStringHelper.EvaluateDBWriteConnectionString))
            {
                var data = false;
                string osql = @"UPDATE ymtsocialcomposite
                               SET IsSync=1
                               WHERE BuyerId=@BuyerId AND SellerId=@SellerId AND OrderId=@OrderId;";
                try
                {
                    var count = conn.Execute(osql, new { BuyerId = buyerId, SellerId = sellerId, OrderId = orderId });
                    if (count > 0)
                    {
                        data = true;
                    }
                }
                catch (Exception ex)
                {
                    ApplicationLog.Error(string.Format("UpdateSocialComposite发生SQL异常SQL:【{0}】", osql), ex);
                }
                conn.Close();
                return data;
            }
        }

        [Obsolete("洗数据用")]
        public static int GetHisEvaluateOrdersCount(List<int> orderIds)
        {
            var sql = string.Format(@"SELECT COUNT(0) FROM orderevalhis where IsSync = 0 {0}",
                orderIds != null && orderIds.Any() ? " and OrderId in @OrderIds" : string.Empty);
            try
            {
                using (var conn = new MySqlConnection(ConnectionStringHelper.EvaluateDBReadConnectionString))
                {
                    return conn.Query<int>(sql, new { OrderIds = orderIds }).FirstOrDefault();
                }
            }
            catch (Exception ex)
            {
                ApplicationLog.Error(string.Format("GetHisEvaluateOrdersCount发生SQL异常：{0}", ex.Message), ex);
            }
            return 0;
        }

        [Obsolete("洗数据用")]
        public static List<EvaluateOrder> GetHisEvaluateOrders(List<int> orderIds, int pagesize = 5000)
        {
            var sql = string.Format(
                @"SELECT OrderId
                        ,SellerId
                        ,BuyerId
                        ,Score ServiceScore
                        ,CreateTime AddTime from orderevalhis where IsSync = 0 {0} limit {1}",
                orderIds != null && orderIds.Any() ? " and OrderId in @OrderIds" : string.Empty, pagesize);
            try
            {
                using (var conn = new MySqlConnection(ConnectionStringHelper.EvaluateDBReadConnectionString))
                {
                    var list = conn.Query<EvaluateOrder>(sql, new { OrderIds = orderIds }).ToList();
                    return list;

                }
            }
            catch (Exception ex)
            {
                ApplicationLog.Error(string.Format("GetHisEvaluateOrders发生SQL异常：{0}", ex.Message), ex);
            }
            return null;
        }

        [Obsolete("洗数据用")]
        public static void UpdateOrderEvalHis(int orderId, int syncState)
        {
            const string sql = @"UPDATE orderevalhis SET IsSync=@syncState WHERE OrderId=@orderId";
            try
            {
                using (var conn = new MySqlConnection(ConnectionStringHelper.EvaluateDBWriteConnectionString))
                {
                    conn.Execute(sql, new { syncState, orderId });
                }

            }
            catch (Exception ex)
            {
                ApplicationLog.Error(string.Format("UpdateOrderEvalHis发生SQL异常：{0}", ex.Message), ex);
                throw;
            }
        }

        [Obsolete("洗数据用")]
        public static bool AddOrderEvalHis(EvaluateOrderStatus orderStatus, List<EvaluateProdStatus> pslist,
            EvaluateOrder orderRes, List<EvaluateProduct> products)
        {
            var orderSql = @"INSERT INTO evaluateorderstatus(OrderId,SellerId,BuyerId,Status,AddTime,UpdateTime)
                                        VALUES(@OrderId,@SellerId,@BuyerId,1,@AddTime,NOW());";

            var prodSql =
                @"INSERT INTO evaluateprodstatus (OrderId,SellerId,BuyerId,ProductId,CatalogId,Status,AddTime,UpdateTime)
                                     VALUES(@OrderId,@SellerId,@BuyerId,@ProductId,@CatalogId,1,@AddTime,NOW());";

            var orderressql =
                @"INSERT INTO evaluateorder (OrderId,SellerId,BuyerId,EvaluateWay,ServiceScore,LogisticsScore,AddTime,UpdateTime,DataType) 
                               VALUES(@OrderId,@SellerId,@BuyerId,@EvaluateWay,@ServiceScore,@LogisticsScore,@AddTime,NOW(),-2)";

            var prodressql = @"INSERT INTO evaluateproduct (
                                 OrderId,SellerId,BuyerId,ProductId,CatalogId,CatalogDesc
                                ,Score,IsSensitive,OrigComments,Comments,ProdEvalTime
                                ,EvaluateTp,UpdateTime,IsDeleted,HasImgs,DataType,HasComment) 
                          VALUES(@OrderId,@SellerId,@BuyerId,@ProductId,@CatalogId,@CatalogDesc
                                ,@Score,@IsSensitive,@OrigComments,@Comments,@ProdEvalTime
                                ,@EvaluateTp,NOW(),0,@HasImgs,-2,@HasComment)";

            using (var conn = new MySqlConnection(ConnectionStringHelper.EvaluateDBWriteConnectionString))
            {
                conn.Open();
                var tran = conn.BeginTransaction();
                try
                {
                    var isSuccess = conn.Execute(orderSql, new
                    {
                        orderStatus.OrderId,
                        orderStatus.SellerId,
                        orderStatus.BuyerId,
                        orderStatus.AddTime
                    }, tran) > 0;

                    bool isResSuccess;
                    if (isSuccess)
                    {
                        isResSuccess = conn.Execute(orderressql, new
                        {
                            orderStatus.OrderId,
                            orderStatus.SellerId,
                            orderStatus.BuyerId,
                            EvaluateWay = EvaluateWay.Buyer,
                            orderRes.ServiceScore,
                            orderRes.LogisticsScore,
                            orderStatus.AddTime
                        }) > 0;
                    }
                    else
                    {
                        tran.Rollback();
                        return false;
                    }

                    if (isResSuccess && pslist != null && pslist.Any())
                    {
                        foreach (var product in pslist)
                        {
                            var isProdSuccess = conn.Execute(prodSql, new
                            {
                                orderStatus.OrderId,
                                orderStatus.SellerId,
                                orderStatus.BuyerId,
                                product.ProductId,
                                product.CatalogId,
                                orderStatus.AddTime
                            }, tran) > 0;
                            if (isProdSuccess)
                            {

                                var prodRes =
                                    products.FirstOrDefault(
                                        p =>
                                            p.ProductId.Equals(product.ProductId) &&
                                            p.CatalogId.Equals(product.CatalogId));
                                if (prodRes == null)
                                {
                                    tran.Rollback();
                                    return false;
                                }

                                if (conn.Execute(prodressql,
                                    new
                                    {
                                        orderStatus.OrderId,
                                        orderStatus.SellerId,
                                        orderStatus.BuyerId,
                                        product.ProductId,
                                        product.CatalogId,
                                        prodRes.CatalogDesc,
                                        prodRes.Score,
                                        prodRes.IsSensitive,
                                        prodRes.OrigComments,
                                        prodRes.Comments,
                                        ProdEvalTime = orderStatus.AddTime,
                                        prodRes.EvaluateTp,
                                        prodRes.HasImgs,
                                        HasComment = string.IsNullOrEmpty(prodRes.Comments)
                                    }, tran) > 0) continue;
                                tran.Rollback();
                                return false;
                            }
                            tran.Rollback();
                            return false;
                        }
                        tran.Commit();
                        return true;
                    }

                    tran.Rollback();
                    return false;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    ApplicationLog.Error(string.Format("AddOrderEvalHis发生SQL异常:{0}", ex.Message), ex);
                }
                finally
                {
                    conn.Close();
                }
            }
            return false;
        }

        /// <summary>
        /// 更新笔记商品评分
        /// </summary>
        /// <returns></returns>
        [Obsolete("洗数据用")]
        public static bool UpdateProductEvalNoteScore(int orderId, int sellerId, int buyerId, List<int> prodEvalIds, decimal score)
        {
            var orderSql =
                @"update evaluateorder set ServiceScore=@score,LogisticsScore=@score,updatetime=now() 
                   where OrderId=@orderId and SellerId=@sellerId and BuyerId=@buyerId and DataType=-1";

            var productSql = @"update evaluateproduct set Score=@score,updatetime=now()
                                where ProdEvalId in @prodEvalIds and OrderId=@orderId and SellerId=@sellerId and BuyerId=@buyerId and DataType=-1";

            using (var conn = new MySqlConnection(ConnectionStringHelper.EvaluateDBWriteConnectionString))
            {
                conn.Open();
                var tran = conn.BeginTransaction();
                try
                {
                    var isSuccess = conn.Execute(orderSql, new
                    {
                        score,
                        orderId,
                        sellerId,
                        buyerId
                    }, tran) > 0;

                    if (isSuccess)
                    {
                        isSuccess = conn.Execute(productSql, new
                        {
                            prodEvalIds,
                            score,
                            orderId,
                            sellerId,
                            buyerId
                        }) > 0;

                        if (isSuccess)
                        {
                            tran.Commit();
                            return true;
                        }
                        else
                        {
                            tran.Rollback();
                            return false;
                        }
                    }
                    else
                    {
                        tran.Rollback();
                        return false;
                    }
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    ApplicationLog.Error(string.Format("UpdateProductEvalNoteScore发生SQL异常:{0}", ex.Message), ex);
                }
                finally
                {
                    conn.Close();
                }
            }
            return false;
        }

        #endregion

        /// <summary>
        /// 写入订单评价状态和商品评价状态
        /// </summary>
        /// <param name="module">订单评价状态</param>
        /// <param name="list">商品评价状态</param>
        /// <returns></returns>
        public static bool AddEvaluateStatus(EvaluateOrderStatus orderStatus, List<EvaluateProdStatus> pslist)
        {
            using (MySqlConnection conn = new MySqlConnection(ConnectionStringHelper.EvaluateDBWriteConnectionString))
            {
                string orderSql = @"INSERT INTO evaluateorderstatus (OrderId,SellerId,BuyerId,Status,AddTime,UpdateTime)
                                        VALUES(@OrderId,@SellerId,@BuyerId,0,NOW(),NOW());";

                string psSql = @"INSERT INTO evaluateprodstatus (OrderId,SellerId,BuyerId,ProductId,CatalogId,Status,AddTime,UpdateTime)
                                     VALUES(@OrderId,@SellerId,@BuyerId,@ProductId,@CatalogId,0,NOW(),NOW());";

                conn.Open();
                var tran = conn.BeginTransaction();
                try
                {
                    //写入订单评价状态
                    var count = conn.Execute(orderSql, new
                    {
                        OrderId = orderStatus.OrderId,
                        SellerId = orderStatus.SellerId,
                        BuyerId = orderStatus.BuyerId
                    }, tran);
                    if (count > 0)
                    {
                        //写入商品评价状态
                        pslist.ForEach(pro =>
                        {
                            conn.Execute(psSql, new
                            {
                                OrderId = orderStatus.OrderId,
                                SellerId = orderStatus.SellerId,
                                BuyerId = orderStatus.BuyerId,
                                ProductId = pro.ProductId,
                                CatalogId = pro.CatalogId
                            }, tran);
                        });
                        tran.Commit();
                        conn.Close();
                        return true;
                    }
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    conn.Close();
                    ApplicationLog.Error(string.Format("AddEvaluateStatus发生SQL异常SQL:【{0}】 SQL:【{1}】", orderSql, psSql), ex);
                }
            }
            return false;
        }

        /// <summary>
        /// 写入评价
        /// </summary>
        /// <param name="module"></param>
        /// <returns></returns>
        public static bool AddEvaluate(EvaluateOrder order, List<EvaluateProductImg> plist)
        {
            if (plist != null && plist.Count > 0)
                plist.RemoveAll(x => x.Score == -1 && string.IsNullOrEmpty(x.OrigComments) && !x.HasImgs);//去除洗数据时没有评价内容的数据

            using (MySqlConnection conn = new MySqlConnection(ConnectionStringHelper.EvaluateDBWriteConnectionString))
            {
                //写入订单评价
                string orderSql = @"INSERT INTO evaluateorder (OrderId,SellerId,BuyerId,EvaluateWay,ServiceScore,LogisticsScore,AddTime,UpdateTime,DataType) VALUES(@OrderId,@SellerId,@BuyerId,@EvaluateWay,@ServiceScore,@LogisticsScore,{0},NOW(),@DataType);";
                //写入商品评价
                string plistSql = @"INSERT INTO evaluateproduct (OrderId,SellerId,BuyerId,ProductId,CatalogId,CatalogDesc,Score,IsSensitive,OrigComments,Comments,ProdEvalTime,EvaluateTp,UpdateTime,IsDeleted,HasImgs,DataType,HasComment) VALUES(@OrderId,@SellerId,@BuyerId,@ProductId,@CatalogId,@CatalogDesc,@Score,@IsSensitive,@OrigComments,@Comments,{0},@EvaluateTp,NOW(),0,@HasImgs,@DataType,@HasComment);
                                    SELECT @@identity;";
                //更新订单评价状态
                string orderStatusSql = @"UPDATE evaluateorderstatus SET Status=1,UpdateTime=NOW(){0} WHERE OrderId=@OrderId AND SellerId=@SellerId AND BuyerId=@BuyerId;";
                //更新商品评价状态
                string pslistSql = @"UPDATE evaluateprodstatus SET STATUS=1,UpdateTime=NOW(){0} WHERE OrderId=@OrderId AND SellerId=@SellerId AND BuyerId=@BuyerId AND ProductId=@ProductId AND CatalogId=@CatalogId;";
                //写入商品图片评价
                string psiListSql = @"INSERT INTO evaluateimgs (ProdEvalId,ImgUrl,AddTime,UpdateTime) VALUES(@ProdEvalId,@ImgUrl,{0},NOW());";

                conn.Open();
                var tran = conn.BeginTransaction();
                try
                {
                    DateTime addTime = DateTime.MinValue;
                    if (plist != null && plist.Count > 0)
                        addTime = plist.Min(x => x.ProdEvalTime);

                    //更新订单评价状态
                    var count = conn.Execute(string.Format(orderStatusSql, addTime != DateTime.MinValue ? " ,AddTime=@AddTime " : " "), new
                    {
                        OrderId = order.OrderId,
                        SellerId = order.SellerId,
                        BuyerId = order.BuyerId,
                        AddTime = addTime
                    }, tran);
                    if (count > 0)
                    {
                        if (plist != null && plist.Count > 0)
                        {
                            //更新商品评价状态
                            plist.ForEach(pro =>
                            {
                                conn.Execute(string.Format(pslistSql, pro.ProdEvalTime != DateTime.MinValue ? " ,AddTime=@ProdEvalTime " : " "), new
                                {
                                    OrderId = order.OrderId,
                                    SellerId = order.SellerId,
                                    BuyerId = order.BuyerId,
                                    ProductId = pro.ProductId,
                                    CatalogId = pro.CatalogId,
                                    ProdEvalTime = pro.ProdEvalTime
                                }, tran);
                            });
                        }
                        //写入订单评价
                        count = conn.Execute(string.Format(orderSql, addTime != DateTime.MinValue ? "@AddTime" : "NOW()"), new
                        {
                            OrderId = order.OrderId,
                            SellerId = order.SellerId,
                            BuyerId = order.BuyerId,
                            EvaluateWay = order.Way,
                            ServiceScore = order.ServiceScore,
                            LogisticsScore = order.LogisticsScore,
                            AddTime = addTime,
                            DataType = order.DataType
                        }, tran);
                        if (count > 0)
                        {
                            if (plist != null && plist.Count > 0)
                            {
                                plist.ForEach(pro =>
                                {
                                    //写入商品评价
                                    var peid = conn.ExecuteScalar(string.Format(plistSql, pro.ProdEvalTime != DateTime.MinValue ? "@ProdEvalTime" : "NOW()"), new
                                    {
                                        OrderId = order.OrderId,
                                        SellerId = order.SellerId,
                                        BuyerId = order.BuyerId,
                                        ProductId = pro.ProductId,
                                        CatalogId = pro.CatalogId,
                                        CatalogDesc = pro.CatalogDesc,
                                        Score = pro.Score,
                                        IsSensitive = pro.IsSensitive,
                                        OrigComments = pro.OrigComments,
                                        Comments = pro.Comments,
                                        EvaluateTp = pro.EvaluateTp,
                                        HasImgs = pro.HasImgs,
                                        ProdEvalTime = pro.ProdEvalTime,
                                        DataType = pro.DataType,
                                        HasComment = string.IsNullOrEmpty(pro.Comments)
                                    }, tran);
                                    if (peid != null)
                                    {
                                        if (pro.Imgs != null && pro.Imgs.Count > 0)
                                        {
                                            pro.Imgs.ForEach(img =>
                                            {
                                                //写入商品图片评价
                                                conn.Execute(string.Format(psiListSql, pro.ProdEvalTime != DateTime.MinValue ? "@ProdEvalTime" : "NOW()"), new
                                                {
                                                    ProdEvalId = Convert.ToInt32(peid),
                                                    ImgUrl = img,
                                                    ProdEvalTime = pro.ProdEvalTime
                                                }, tran);
                                            });
                                        }
                                    }
                                });
                            }

                            tran.Commit();
                            conn.Close();
                            return true;
                        }
                    }
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    conn.Close();
                    ApplicationLog.Error(string.Format("AddEvaluate发生SQL异常SQL:【{0}】 SQL:【{1}】 SQL:【{2}】 SQL:【{3}】 SQL:【{4}】 订单号：【{5}】", orderSql, plistSql, orderStatusSql, pslistSql, psiListSql, order.OrderId), ex);
                }
            }
            return false;
        }

        /// <summary>
        /// 更新商品评价表
        /// </summary>
        /// <param name="module"></param>
        /// <returns></returns>
        public static EvaluateProduct UpdateEvaluateProduct(int buyerId, int prodEvalId, string productId)
        {
            using (MySqlConnection conn = new MySqlConnection(ConnectionStringHelper.EvaluateDBWriteConnectionString))
            {
                var data = new EvaluateProduct();
                string osql = @"UPDATE evaluateproduct
                               SET IsDeleted=1,UpdateTime=NOW()
                               WHERE BuyerId=@BuyerId AND ProdEvalId=@ProdEvalId AND ProductId=@ProductId AND IsDeleted=0;";
                string qsql = @"SELECT ProdEvalId,OrderId,SellerId,BuyerId,ProductId,CatalogId,CatalogDesc,Score,IsSensitive,OrigComments,Comments,ProdEvalTime,EvaluateTp,UpdateTime,IsDeleted,HasImgs
                               FROM evaluateproduct
                               WHERE BuyerId=@BuyerId AND ProdEvalId=@ProdEvalId AND ProductId=@ProductId;";
                try
                {
                    var count = conn.Execute(osql, new { BuyerId = buyerId, ProdEvalId = prodEvalId, ProductId = productId });
                    if (count > 0)
                    {
                        data = conn.Query<EvaluateProduct>(qsql, new { BuyerId = buyerId, ProdEvalId = prodEvalId, ProductId = productId }).FirstOrDefault();
                    }
                    conn.Close();
                    return data;
                }
                catch (Exception ex)
                {
                    conn.Close();
                    ApplicationLog.Error(string.Format("UpdateEvaluateProduct发生SQL异常SQL:【{0}】 SQL:【{1}】", osql, qsql), ex);
                }
                return null;
            }
        }

        public static bool AddUserExpLog(int errorCode, string reqParam)
        {
            const string sql = @"INSERT INTO AddUserExpLog(ErrorCode,ReqParam,AddTime,UpdateTime) SELECT @errorCode,@reqParam,NOW(),NOW()";

            try
            {
                using (var conn = new MySqlConnection(ConnectionStringHelper.EvaluateDBWriteConnectionString))
                {
                    return conn.Execute(sql, new { errorCode, reqParam }) > 0;
                }
            }
            catch (Exception ex)
            {
                ApplicationLog.Error("AddUserExpLog发生异常", ex);
            }

            return false;
        }

        /// <summary>
        /// 评价回复
        /// </summary>
        /// <param name="reply"></param>
        /// <returns></returns>
        public static bool AddReply(EvaluateReply reply)
        {
            var param = new DynamicParameters(reply);
            var sql = @"INSERT INTO evaluatereply(ProdEvalId,IsSensitive,OrigReply,Reply,ReplyTime,IsDeleted,UpdateTime)
                        SELECT @ProdEvalId,@IsSensitive,@OrigReply,@Reply,NOW(),0,NOW()";
            using (var conn = new MySqlConnection(ConnectionStringHelper.EvaluateDBWriteConnectionString))
            {

                conn.Open();
                var tran = conn.BeginTransaction();
                try
                {
                    var isSuccess = conn.Execute(sql, param, tran) > 0;
                    if (isSuccess)
                    {
                        sql = "UPDATE evaluateproduct SET HasReply = 1 WHERE ProdEvalId=@ProdEvalId";
                        if (conn.Execute(sql, new { reply.ProdEvalId }, tran) > 0)
                        {
                            tran.Commit();
                            return true;
                        }
                        else
                        {
                            tran.Rollback();
                            return false;
                        }
                    }
                }
                catch (Exception ex)
                {
                    ApplicationLog.Error("AddReply发生SQL异常", ex);
                    tran.Rollback();
                }
                finally
                {
                    conn.Close();
                }
            }
            return false;
        }
    }
}
